<template>
  <el-form :inline="true" :model="dataForm" :rules="dataRule" ref="form">
    <el-form-item prop="keyword">
      <el-input v-model="dataForm.keyword" placeholder="套餐标题/订单编号"
                size="medium" class="keyword" maxlength="30" clearable/>
    </el-form-item>
    <el-form-item prop="medium">
      <el-button type="primary" :icon="Search"
                 size="medium" @click="searchHandle()">查询
      </el-button>
    </el-form-item>
    <el-form-item class="mold">
      <el-radio-group v-model="dataForm.statusLabel" size="medium"
                      @change="searchHandle()">
        <el-radio-button label="全部"></el-radio-button>
        <el-radio-button label="未付款"></el-radio-button>
        <el-radio-button label="已付款"></el-radio-button>
      </el-radio-group>
    </el-form-item>
  </el-form>
  <div class="order-list" v-show="!empty">
    <div class="order" v-for="one in data.dataList">
      <div class="header">
        <div class="datetime">{{ one.createTime }}</div>
        <div class="uuid">
          订单号,
          <span>{{ one.outTradeNO }}</span>
        </div>
        <div class="detail" @click="searchDetailHandle(one.snapshotId)">
          查看商品详情
        </div>
      </div>
      <div class="content">
        <img :src="one.goodsImage" class="image"/>
        <div class="info">
          <h4>{{ one.goodsTitle }}</h4>
          <p>{{ one.goodsDescription }}</p>
        </div>
        <div class="price">
          <span class="label">套餐价格</span>
          <span class="value">￥{{ one.goodsPrice }}</span>
        </div>
        <div class="number">
          <span class="label">购买数量</span>
          <span class="value">￥{{ one.number }}</span>
        </div>
        <div class="amount">
          <span class="label">合计</span>
          <span class="value">￥{{ one.amount }}</span>
        </div>
        <div class="status">
          <span class="label">状态</span>
          <span class="value">￥{{ one.status }}</span>
        </div>
        <div class="operate">
          <el-button v-if="one.status=='未付款'" type="primary"
                     :disable="one.disabled"
                     @click="paymentHandle(one.outTradeNo)">
            付款
          </el-button>
          <el-button v-if="one.status=='未付款'" type="danger"
                     @click="closrOrderHandle(one.id)">
            取消订单
          </el-button>
          <el-button v-if="one.status=='已付款'" type="primary"
                     :disable="one.appointCount==one.number"
                     @click="appointHandle(one.id,one.number,one.appointCount)">
            预约体检
          </el-button>
          <el-button v-if="one.status=='已付款'">获取发票</el-button>
          <el-button v-if="one.status=='已付款'" type="danger"
                     :disable="one.appointCount==one.number"
                     @click="refundHandle(one.id)">
            退款
          </el-button>
        </div>
      </div>
    </div>
    <el-pagination
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
        :current-page="data.pageIndex"
        :page-size="data.pageSize"
        :page-sizes="[10, 20, 50]"
        :total="data.totalCount"
        layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
  </div>
  <div class="empty" v-show="empty">
    <el-empty :image-size="200"/>
  </div>
  <el-dialog
      title="体检预约"
      :close-on-click-modal="false"
      v-model="appointDialog.visible"
      width="550px"
  >
    <el-form
        :model="appointDialog.dataForm"
        ref="dialogForm"
        :rules="appointDialog.dataRule"
        label-width="80px"
    >
      <fieldset class="appointment">
        <legend>
          <h4>我的预约</h4>
        </legend>
        <el-form-item label="预约日期" prop="date">
          <el-date-picker
              v-model="appointDialog.dataForm.date"
              type="date"
              placeholder="选择日期"
              size="medium"
              :editable="false"
              format="YYYY.MM.DD"
              value-format="YYYY-MM-DD"
              :disabled-date="disabledDate"
          />
          <span class="desc">提示:不可预约今日</span>
        </el-form-item>
        <el-form-item label="体检人" prop="name">
          <el-input
              v-model="appointDialog.dataForm.name"
              size="medium"
              placeholder="输入姓名"
              maxlength="18"
              clearable
          />
        </el-form-item>
        <el-form-item label="身份证号" prop="pid">
          <el-input
              v-model="appointDialog.dataForm.pid"
              size="medium"
              placeholder="输入身份证号"
              maxlength="18"
              clearable
          />
        </el-form-item>
        <el-form-item label="电话号码" prop="tel">
          <el-input
              v-model="appointDialog.dataForm.tel"
              size="medium"
              placeholder="输入电话号码"
              maxlength="11"
              clearable
          />
        </el-form-item>
        <el-form-item label="邮寄地址" prop="mailingAddress">
          <el-input
              v-model="appointDialog.dataForm.mailingAddress"
              size="medium"
              placeholder="输入接收体检报告的邮寄地址"
              maxlength="100"
              clearable
          />
        </el-form-item>
        <el-form-item label="公司名称" prop="company">
          <el-input
              v-model="appointDialog.dataForm.company"
              size="medium"
              placeholder="输入公司名称"
              maxlength="100"
              clearable
          />
        </el-form-item>
      </fieldset>
    </el-form>
    <template>
      <div slot="footer" class="dialog-footer">
        <el-button size="medium" @click="appointDialog.visible = false">取消</el-button>
        <el-button type="primary" size="medium" @click="dataFormSubmit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {getCurrentInstance, reactive, ref} from "vue";
import {Search} from "@element-plus/icons-vue";
import {dayjs} from "element-plus";


// dayjs.extend(isBetween)
const {proxy} = getCurrentInstance();
let empty = ref(false);
const dataForm = reactive({
  keyword: null,
  statusLabel: null,
  status: null
});
const data = reactive({
  dataList: [],
  pageIndex: 1,
  pageSize: 10,
  totalCount: 0,
  loading: false,
  selections: []
})
const dataRule = reactive({
  keyword: [
    {
      required: false,
      pattern: /^[a-zA-Z0-9\u4e00-\u9fa5]{1,30}$/,
      message: '关键字只能是字母、数字或汉字，并且长度为1到30个字符。',
    }
  ]
});
const appointDialog = reactive({
  visible: false,
  number: null,
  appointCount: null,
  dataForm: {
    orderId: null,
    date: null,
    name: null,
    pid: null,
    tel: null,
    mailingAddress: null,
    company: null
  },
  dataRule: {
    date: [
      {required: true, message: '日期不能为空', trigger: 'change'}
    ],
    name: [
      {required: true, message: '姓名不能为空', trigger: 'blur'},
      {pattern: /^[\u4e00-\u9fa5]{2,10}$/, message: '姓名格式错误', trigger: 'blur'}
    ],
    pid: [
      {required: true, message: '身份证号不能为空', trigger: 'blur'},
      {pattern: /^[1-9]\d{16}[\dXx]$/, message: '身份证号格式错误', trigger: 'blur'}
    ],
    tel: [
      {required: true, message: '电话号码不能为空', trigger: 'blur'},
      {pattern: /^1[3-9]\d{9}$/, message: '电话号码格式错误', trigger: 'blur'}
    ],
    mailingAddress: [
      {required: true, message: '邮寄地址不能为空', trigger: 'blur'},
      {pattern: /^[0-9A-Za-z\u4e00-\u9fa5\-#]{10,100}$/, message: '邮寄地址格式错误', trigger: 'blur'}
    ],
    company: [
      {required: false},
      {pattern: /^[0-9A-Za-z\u4e00-\u9fa5\-#]{2,100}$/, message: '公司名称格式错误', trigger: 'blur'}
    ]
  }
})

function loadDataList() {
  data.loading = true;
  if (dataForm.statusLabel == '全部') {
    dataForm.status = null; // If statusLabel is '全部', set status to null
  } else if (dataForm.statusLabel == '1') {
    dataForm.status = 1; // If statusLabel is '1', set status to 1
  } else {
    dataForm.status = 3; // For any other value, set status to 3
  }

// Prepare the JSON object for the request
  let json = {
    page: data.pageIndex,
    length: data.pageSize,
    keyword: dataForm.keyword,
    status: dataForm.status
  };
  proxy.$http("/front/order/searchByPage", "POST", json, true, function (resp) {
    // Define status enum
    let statusEnum = {
      "1": "未付款",
      "2": "已关闭",
      "3": "已付款",
      "4": "已退货",
      "5": "已预约",
      "6": "已结束"
    };

    let page = resp.result;
    let list = page.list;

    // Process the order list
    for (let one of list) {
      one.goodsImage = `${proxy.$minioUrl}/${one.goodsImage}`; // Construct the image URL
      one.status = statusEnum[one.status + ""]; // Convert status to string and map to statusEnum
    }

    // Assign processed data to the data object
    data.datalist = list;
    data.totalCount = page.totalCount;
    data.loading = false; // Set loading to false after data is processed

    // Handle case when list is empty
    if (list.length === 0) {
      console.log("No data found");
      // Add additional handling for empty data if needed
    }
  });
}

function refundHandle(id) {
  proxy.$confirm(
      "您确定要执行退款吗？", // 修正了引号和文字
      "提示信息",
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    let json = {id: id};

    // 发送退款请求
    proxy.$http('/front/order/refund', 'POST', json, true, function (resp) {
      if (resp.result) {
        proxy.$message({
          message: '已经申请原路退回款项，稍后请查收退款。',
          type: 'success',
          duration: 1200
        });
      } else {
        proxy.$message({
          message: "退款申请失败，请联系客服。",
          type: 'error',
          duration: 1200
        });
      }
    });
  })
}

function disabledDate(date) {
  let bool = dayjs(date).isBetween(dayjs(), dayjs().add(61, 'day'));
  return !bool
}


function appointHandle(id, number, appointCount) {
  if (appointCount === 0) {
    proxy.$confirm("该订单预约体检后将无法退敷，是否预约体检?", "提示信息", {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      appointDialog.visible = true;
      appointDialog.dataForm.orderId = id;
      appointDialog.number = number;
      appointDialog.appointCount = ++appointCount;
      proxy.$nextTick(() => {
        proxy.$refs['dialogform'].resetFields();
      });
    });
  }
}
function dataFormSubmit() {
  proxy.$refs['dialogForm'].validate(valid => {
    if (valid) {
      let json = {
        orderId: appointDialog.dataForm.orderId,
        date: appointDialog.dataForm.date,
        name: appointDialog.dataForm.name,
        pid: appointDialog.dataForm.pid,
        tel: appointDialog.dataForm.tel,
        mailingAddress: appointDialog.dataForm.mailingAddress,
        company: appointDialog.dataForm.company
      };
      proxy.$http('/front/appointment/insert', 'POST', json, true, function (resp) {
        let result = resp.result;
        if (result === "预约成功") {
          proxy.$message({
            message: result,
            type: "success"
          });
        } else {
          proxy.$message({
            message: "预约失败，请稍后重试",
            type: "error"
          });
        }
      });
    }
  });
}


loadDataList();
</script>
<style scoped lang="less">
@import "order_list";
</style>
